#include "dou.h"
#include "ui_dou.h"
#include "QDebug"

dou *douzhizhen=NULL;

void sendbyte(unsigned char temp)
{
    douzhizhen->dou_sendbyte(temp);
}

dou::dou(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::dou)
{
    ui->setupUi(this);
    douzhizhen=this;
    HekrInit(sendbyte);
    SerialPortUpdata();
//    startTimer(1000);
}

dou::~dou()
{
    delete ui;
}

void dou::timerEvent(QTimerEvent *event)
{
    Q_UNUSED(event);
    SerialPortUpdata();
    if(my_serialport==NULL)
    {
        ui->pushButton_9->setText("打开串口");
    }
}

void dou::SerialPortUpdata()
{
    qDebug() << "更新可用串口信息";
    int tempxuhao=ui->comboBox->currentIndex();
    QString temp =ui->comboBox->currentText();
    ui->comboBox->clear();
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        qDebug()<<"Name:"<<info.portName();
        qDebug()<<"Description:"<<info.description();
        qDebug()<<"Manufacturer:"<<info.manufacturer();
        ui->comboBox->addItem(info.portName());
    }
    ui->comboBox->setCurrentIndex(tempxuhao);

/*    if(ui->comboBox->currentText()!=temp)       //检测到原先选中项丢失
    {
        ui->comboBox->setCurrentText("");
        if(my_serialport!=NULL)
        {
            my_serialport->close();
            delete my_serialport;
            my_serialport=NULL;
        }
    }*/
    if(ui->comboBox->currentText().isNull())
    {
        ui->comboBox->addItem("未发现可用串口");
    }
}


void dou::openserialport()
{
    my_serialport = new QSerialPort(this);
    my_serialport->setPortName(ui->comboBox->currentText());
    if(my_serialport->open(QIODevice::ReadWrite))
    {
        //设置波特率为9600
        my_serialport->setBaudRate(9600);
        //设置数据位为8位
        my_serialport->setDataBits(QSerialPort::Data8);
        //关闭校验位
        my_serialport->setParity(QSerialPort::NoParity);
        //关闭流控制
        my_serialport->setFlowControl(QSerialPort::NoFlowControl);
        //设置停止位为1位
        my_serialport->setStopBits(QSerialPort::OneStop);

        connect(my_serialport, SIGNAL(readyRead()), this, SLOT(readUARTbuff()));
        ui->pushButton_9->setText("发送");
    }
    else
    {
        my_serialport->close();
        delete my_serialport;
        my_serialport=NULL;
    }
}

void dou::on_pushButton_9_clicked()    //发送按键点击事件
{
    if(my_serialport==NULL)   //判断串口是否已经打开
    {
        openserialport();       //打开串口
        qDebug()<< "打开串口";
    }
    else
    {
        //获取发送区的数据
        QString sendData = ui->textEdit->toPlainText();
        //转换数据
        unsigned char len= Qstringtohex(&sendData,valid_data);
        if(len!=0)   //是否为空
        {
            //发送数据
            HekrValidDataUpload(len);
            qDebug()<< "发送数据";
        }

    }
}

void dou::readUARTbuff()            //读取串口接收缓存
{
    //读取串口数据
    QByteArray readComData = my_serialport->readAll();

    //将读到的数据显示到数据接收区中
    if(readComData != NULL)
    {
        ui->textBrowser->append(readComData.toHex());
        unsigned char *dou_r =(unsigned char*)readComData.data();
        qDebug()<<"接收："<<dou_r;
        unsigned char mingling = HekrRecvDataHandle(dou_r);

        if(mingling==ValidDataUpdate)    //wifi模块下发指令
        {

        }
        else if(mingling==MCU_ControlModuleACK)   //模块操作指令响应
        {

        }
        else if(mingling ==HekrModuleStateUpdate)  //模块状态返回
        {
            ui->label_8->setText(HekrModule[ModuleStatus->Mode]);   //更新显示模块模式
            ui->label_9->setText(ModuleWIFICode[ModuleStatus->WIFI_Status]);   //更新显示WIFI状态
            ui->label_10->setText(ModuleCloudCode[ModuleStatus->CloudStatus]);    //更新显示云连接状态
            ui->label_11->setText(Modulexinhao[ModuleStatus->SignalStrength]);    //更新显示信号强度
            ui->label_12->setText(Modulechangce[ModuleStatus->Reserved]);    //更新连通性测试
        }

    }
    //清除缓冲区
    readComData.clear();
}

unsigned char dou::Chartohex(char temp)
{
    if(temp>='0'&&temp<='9')
    {
        return temp-'0';
    }
    else if(temp>='a'&&temp<='f')
    {
        return temp-'a'+10;
    }
    else if(temp>='A'&&temp<='F')
    {
        return temp-'A'+10;
    }
    else
        return 0;
}

unsigned char dou::Qstringtohex(QString *str,unsigned char *temp)
{
    int strlen=str->length();
    int i;
    if(strlen%2==0)
    {
        char *strtemp = str->toLatin1().data();
        for(i=0;i<strlen/2;i++)
        {
            *(temp+i)= Chartohex(*(strtemp+i*2)) *16+Chartohex(*(strtemp+i*2+1));
        }
        return strlen/2;
    }
    else
        return 0;
}

void dou::dou_sendbyte(unsigned char temp)    //发送一字节
{
    char dad;
    dad=temp;
    //写入缓冲区
    if(my_serialport!=NULL)
    {
        my_serialport->write(&dad,1);
    }
}

void dou::on_pushButton_6_clicked()    //查询模块版本按键点击事件
{
    Module_Firmware_Versions_Function();
}

void dou::on_pushButton_clicked()      //查询模块状态按键点击事件
{
    Module_State_Function();
}

void dou::on_pushButton_7_clicked()     //Prodkey匹配查询按键点击事件
{
    Module_ProdKey_Get_Function();
}

void dou::on_pushButton_8_clicked()     //设置Prodkey按键点击事件
{
    QString Qprodkey = ui->lineEdit_2->text();
    if(Qprodkey.length()==32)
    {
        unsigned char temp[16];
        Qstringtohex(&Qprodkey,temp);
        Set_ProdKey(temp);
        qDebug() <<"set prodkey";
    }
}

void dou::on_pushButton_2_clicked()     //重启模块按键点击事件
{
    Module_Soft_Reboot_Function();
}

void dou::on_pushButton_4_clicked()     //休眠模块按键点击事件
{
    Module_Set_Sleep_Function();
}

void dou::on_pushButton_5_clicked()     //唤醒模块按键点击事件
{
    Module_Weakup_Function();
}

void dou::on_pushButton_3_clicked()     //进入配网模式按键点击事件
{
    Hekr_Config_Function();
}
